package cn.edu.cdcas.controller;

import cn.edu.cdcas.entity.Student;
import cn.edu.cdcas.service.ExamService;
import cn.edu.cdcas.service.StudentService;
import cn.edu.cdcas.utils.CaptchaUtil;
import cn.edu.cdcas.utils.Constant;
import cn.edu.cdcas.vo.QuestionNum;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Controller
@RequestMapping("/")
public class LoginController {

    @Resource
    StudentService studentService;

    @Resource
    ExamService examService;

    @RequestMapping("login")
    public String login(Model model, ModelMap modelMap) throws Exception {
        return "/login";
    }

    @RequestMapping(value = "login.json", method = {RequestMethod.POST})
    @ResponseBody
    public Map<String, Object> login(HttpSession httpSession, String studentNo, String schoolNo, ModelMap modelMap, HttpServletRequest request,
                                     HttpServletResponse response, RedirectAttributes redirectAttributes) {
        String captcha = request.getParameter("captcha");
        String validateCode = (String) request.getSession().getAttribute(CaptchaUtil.KEY_CAPTCHA);
        Map<String, Object> map = new HashMap<>();

        if (StringUtils.isNotBlank(captcha) && validateCode.equals(captcha)) {//判断验证码是否正确
            Student student = studentService.queryByStudentNo(studentNo, schoolNo);
            if (student == null) {
                map.put("success", false);
                map.put("message", "登录名或密码错误！");
                return map;
            }
            int min = student.getExamTime();
			/*student.setExamTime(min*60);
			student.setMakeUpTime(min*60);*/
            if (student.getExamState() == 1 && student.getMakeUpState() == 0) { //初考正在考试
                Date examStart = student.getExamStart();//首次登陆时间
                if (examStart != null) {
                    Date nowDate = new Date();
                    long c = (nowDate.getTime() - examStart.getTime()) / (1000 * 60);
                    student.setSurExamTime(min - (int) c); //剩余时间
                } else {
                    student.setSurExamTime(min);
                }
            } else if (student.getExamState() == 3 && student.getMakeUpState() == 1) { //补考正在考试
                Date makeUpStart = student.getMakeUpStart();
                if (makeUpStart != null) {
                    Date nowDate = new Date();
                    long c = (nowDate.getTime() - makeUpStart.getTime()) / (1000 * 60);
                    min = (int) c;
                    student.setSurExamTime(min - (int) c);
                } else {
                    student.setSurExamTime(min);
                }
            } else {
                student.setSurExamTime(min);
            }

            request.getSession().setAttribute(Constant.USER_IN_SESSION, student);//登录成功把用户存入Session
            request.getSession().setAttribute("EXAMTIME_IN_SESSION", min);
            student.setLastLoginTime(new Date());
            student.setLastLoginIp(getIpAddr(request));
            studentService.updateLoginState(student);//更新登录状态
            // 当前考试类型
            int examId = student.getExamId();
            QuestionNum questionNum = examService.findNum(examId);
            httpSession.setAttribute("questionNum", questionNum); //题数分数
            map.put("success", true);
            return map;
        } else {
            map.put("success", false);
            map.put("message", "验证码错误！");
            return map;
        }
    }

    @RequestMapping(value = "logout", method = {RequestMethod.GET})
    public String loginOut(HttpServletRequest request) throws Exception {
        request.getSession().removeAttribute(Constant.USER_IN_SESSION);//登录成功把用户存入Session
        return "/login";
    }

    /**
     * @param request
     * @param response
     * @描述:登录验证码
     * @方法名称 :getImage
     * @作者 :HuanGe
     * @创建日期 :2015年6月6日 上午12:23:00
     */
    @RequestMapping(value = "/getCaptcha")
    public void getImage(HttpServletRequest request, HttpServletResponse response) throws Exception {
        response.setContentType("image/jpeg");
        // 不缓存此内容
        response.setHeader("Pragma", "No-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expire", 0);
//        try {

        HttpSession session = request.getSession();

        CaptchaUtil tool = new CaptchaUtil();
        StringBuffer code = new StringBuffer();
        BufferedImage image = tool.genRandomCodeImage(code);
        session.removeAttribute(CaptchaUtil.KEY_CAPTCHA);
        session.setAttribute(CaptchaUtil.KEY_CAPTCHA, code.toString());

        // 将内存中的图片通过流动形式输出到客户端
        ImageIO.write(image, "JPEG", response.getOutputStream());

//        } catch (Exception e) {
//        }
    }

    public String getIpAddr(HttpServletRequest request) {
        String ip = request.getHeader("X-Real-IP");
        if (!StringUtils.isBlank(ip) && !"unknown".equalsIgnoreCase(ip)) {
            return ip;
        }
        ip = request.getHeader("X-Forwarded-For");
        if (!StringUtils.isBlank(ip) && !"unknown".equalsIgnoreCase(ip)) {
            // 多次反向代理后会有多个IP值，第一个为真实IP。
            int index = ip.indexOf(',');
            if (index != -1) {
                return ip.substring(0, index);
            } else {
                return ip;
            }
        } else {
            return request.getRemoteAddr();
        }
    }
}
